/*
 * @Author: xiaosihan 
 * @Date: 2024-08-01 15:32:26 
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2025-09-26 21:45:28
 */

import shortid from "shortid";
import pathBrowserify from "path-browserify";
import SparkMD5 from "spark-md5";
import Api from "@/api/Api";

class Utils {

    constructor() {
        console.log("isWX", this.isWX);
        console.log("isBrowser", this.isBrowser);
        console.log("isDev", this.isDev);
        console.log("isTest", this.isTest);
        console.log("isProd", this.isProd);
    }

    // 微信小程序环境
    isWX = (typeof wx === 'object');

    // 浏览器环境
    isBrowser = (!this.isWX && typeof window === 'object');

    // 开发环境
    isDev = (() => {
        if (this.isBrowser) {
            return (process.env.NODE_ENV === "development");
        } else if (this.isWX) {
            return wx.getAccountInfoSync().miniProgram.envVersion === "develop";
        }
        return false;
    })();

    // 测试环境
    isTest = (() => {
        if (this.isBrowser) {
            return (process.env.NODE_ENV === "test");
        } else if (this.isWX) {
            return wx.getAccountInfoSync().miniProgram.envVersion === "trial";
        }
        return false;
    })();

    // 正式环境
    isProd = (() => {
        if (this.isBrowser) {
            return (process.env.NODE_ENV === "production");
        } else if (this.isWX) {
            return wx.getAccountInfoSync().miniProgram.envVersion === "release";
        }
        return false;
    })();

    // 苹果手机
    isIPhone = this.isWX && wx.getDeviceInfo().brand === "iPhone";

    // 华为
    isHuawei = this.isWX && wx.getDeviceInfo().brand === "HUAWEI";

    // 封装本地存储设置方法
    setStorageSync(key: string, value: string) {
        if (this.isBrowser) {
            localStorage.setItem(key, value);
        } else if (this.isWX) {
            wx.setStorageSync(key, value);
        }
    }

    // 封装本地存储获取方法
    getStorageSync(key: string) {
        if (this.isBrowser) {
            return localStorage.getItem(key);
        } else if (this.isWX) {
            return wx.getStorageSync(key);
        }
    }

    // 封装本地存储删除方法
    removeStorageSync(key: string) {
        if (this.isBrowser) {
            localStorage.removeItem(key);
        } else if (this.isWX) {
            wx.removeStorageSync(key);
        }
    }

    // 封装本地存储清空方法
    clearStorageSync() {
        if (this.isBrowser) {
            localStorage.clear();
        } else if (this.isWX) {
            wx.clearStorageSync();
        }
    }

    // 生成短ID
    uuid() {
        const shortId = shortid();
        return shortId;
    }

    // 解析URL路径
    parseUrl(url: string) {
        const { root, dir, base, ext, name, } = pathBrowserify.parse(url);
        return { root, dir, base, ext, name };
    }

    // 获取文件指纹
    async getFileMD5(file: File) {
        return new Promise((resolve) => {
            const spark = new SparkMD5.ArrayBuffer();
            const reader = new FileReader();

            reader.onload = (e) => {
                spark.append(e.target!.result as ArrayBuffer);
                resolve(spark.end()); // 返回 MD5 哈希值
            };

            reader.readAsArrayBuffer(file);
        });
    }

    ossSuffix(src: string = "", maxSide?: number) {

        // 输入空,就直接返回空
        if (!src) {
            return src;
        }

        let newSrc = (src || "")
            .replace(/(\?|&)(x-oss-process=.*?)(?=&|$)/, '')
            .replace(/^https?:/, "")
            .replace(Api.ossRoot, "")
        // .replace(/^\/\/upload-custom\.oss-cn-beijing\.aliyuncs.com/, "");

        // 不处理占位图
        if (newSrc !== "./UTlogo.svg") {
            newSrc = `/${newSrc}`.replace(/\/+/, "/"); // 删除重复的斜杠，防止拼接出错
            newSrc = `${Api.ossRoot}${newSrc}`;
        }

        if (maxSide && !src.endsWith('.svg')) {
            newSrc += `?x-oss-process=image/resize,m_lfit,w_${maxSide},h_${maxSide}`;
        }

        return `https:${newSrc}`; //补回https前缀
        // return `http:${newSrc}`; //补回https前缀
    }

}
// Utils类结束

// 创建Utils实例
const utils = new Utils();
// 导出utils实例
export default utils;